package com.kb5173.search.words.dao.nosql.impl;

import com.kb5173.search.common.utils.RedisKeyHelper;
import com.kb5173.search.words.dao.nosql.IWordsRedisDAO;
import com.kb5173.framework.dataaccess.redis.AbstractRedisDAO;
import com.kb5173.framework.shared.entity.BaseEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author Chengfei.Sun
 */
@Repository
public class WordsRedisDAOImpl extends AbstractRedisDAO<BaseEntity> implements IWordsRedisDAO {
    @Autowired
    @Qualifier("redisTemplate")
    @Override
    public void setTemplate(StringRedisTemplate template) {
        super.template = template;
    };

    @Override
    public void addWords(List<String> words) {
        /**
         * 采用zSet方式存储：以免有重复的词汇
         */
        Date nowTime = new Date();

        for(String word : words){
            zSetOps.add(RedisKeyHelper.words(), word, nowTime.getTime());
        }
    }

    @Override
    public List<String> getWords() {
        String lastReadIndex = valueOps.get(RedisKeyHelper.lastWordsIndex());
        if(StringUtils.isEmpty(lastReadIndex)){
            lastReadIndex = "0";
        }
        long currentIndex = zSetOps.size(RedisKeyHelper.words());

        /**
         * 获取从未被读取过的词汇，这里用索引范围来限制(上次读取的索引~当前索引)，区间是[]
         */
        Set<String> result = zSetOps.range(RedisKeyHelper.words(), Long.valueOf(lastReadIndex), currentIndex);

        if (result == null || result.size() == 0) {
            return null;
        }

        valueOps.set(RedisKeyHelper.lastWordsIndex(), String.valueOf(currentIndex));

        return new ArrayList<String>(result);
    }
}
